package com.breeze.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginCheckFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 获取请求地址
        String uri = request.getRequestURI();
        // 放行资源
        if (uri.endsWith("/login") || uri.endsWith("/register") || uri.contains("/static")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 获取响应体对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        // 获取token
        String token = request.getHeader("token");
        if (token == null || isTokenEqual(token)){
            Map<String,Object> map = new HashMap();
            map.put("success",false);
            map.put("message","未登录！");
            map.put("code","403");
            map.put("data",null);
            //设置响应中文编码
            response.setContentType("application/json;charset=utf-8");
            //把map转成json字符串，写到浏览器
            String resultJsonString = JSON.toJSONString(map);
            try {
                response.getWriter().println(resultJsonString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 阻止程序继续运行
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }

        return null;
    }

    public Boolean isTokenEqual(String token){
        return false;
    }
}
